/**
 * Created by jocky on 2018/4/8.
 */

var templateObj = {
    /**
     * 分配模板
     *
     * @param clientSN 用户
     * @param alias 姓名
     * @param type 1代理，2客户
     * @param uid
     */
    assignForm: function (clientSN, alias, type, uid) {
        $.get('/template/assign-form', {type: type, uid: uid}, function (html) {
            var title = "为用户 " + clientSN;
            if ($.trim(alias) != "") {
                title += "[" + $.trim(alias) + "]"
            }
            title += " 分配模板";
            $('#modal_pop2_title').html(title);
            $('#modal_pop2_body').html(html);
            $('#modal_pop2').modal('show');
        });
    },

    /**
     *  为用户分配模板
     *
     * @param uid 用户ID
     * @param type 1代理，2交易客户
     */
    assignTemplate: function (uid, type) {
        var params = {};
        params.type = type;
        params.uid = uid;

        var validFlag = true;
        var search = $('#assign_template_form').find('select,input');
        $.each(search, function (i, v) {
            var name = $(v).attr('name');
            var val = $(v).val();
            if (name) {
                if ((v.tagName).toLowerCase() == 'select' && val == 0) {
                    validFlag = false;
                    new PNotify({
                        title: '错误提醒',
                        text: $(v).attr('data-error'),
                        delay: 5000,
                        styling: 'bootstrap3'
                    });

                    return false;
                }
                params[name] = $(v).val();
            }
        });

        if (!validFlag) return false;

        swal({
            title: '确定应用此模板吗?',
            text: type == 1 ? "当用户基于现有模板创建了自己的模板库时，可能会导致切换失败" : "",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then(function () {
            $.post('/template/assign', params, function (json) {
                var obj = {
                    title: '操作通知',
                    text: json.msg,
                    styling: 'bootstrap3',
                    delay: 5000,
                    type: ''
                };
                if (json.code == 1) {
                    obj.type = 'info';
                    obj.addclass = 'dark';
                } else {
                    obj.type = 'error';
                }
                new PNotify(obj);
            }, 'json')
        }, function (dismiss) {

        });
    },

    /**
     * 模板列表
     *
     * @param type 1:首尾页,2:翻页,3跳页
     * @param direction type=1时该参数表示首页或尾页,type=2时该参数表示上一页或下一页
     */
    lists: function (type, direction) {
        //显示loading
        show_loading_table('template_lists_table', 9);

        var params = {};
        params.isRender = 2;//ajax调用

        var pageNo_dom = 'template_lists_pageNo';
        var pageTotal_dom = 'template_lists_pageTotal';
        params.pageNo = getPageNo(pageNo_dom, pageTotal_dom, type, direction);
        params.clientSN = $.trim($('#template_lists_search').val());

        $.getJSON('/template/lists', params, function (json) {
            $("#" + pageNo_dom).val(parseInt(json.pageNo));
            $("#" + pageTotal_dom).html(parseInt(json.pageTotal));

            var tr = "";
            $.each(json.lists, function (i, v) {
                var style = v.is_default == 1 ? 'style="color:red;"' : '';
                var icon = v.is_default == 1 ? 'fa-check' : 'fa-close';
                var status = "<i class='fa " + icon + "' " + style + "></i>";
                tr += "<tr>";
                if (json.uid != v.uid) {
                    tr += "<td><a href='javascript:void(0)' title='查看 / 修改账户信息' onclick=\"agentObj.setForm(" + v.uid + ")\">" + v.clientSN + "</a></td>";
                } else {
                    tr += "<td>" + v.clientSN + "</td>";
                }

                tr += "<td>" + v.alias + "</td>";
                tr += "<td>" + v.title + "</td>";
                tr += "<td class='text-center'>" + status + "</td>";
                tr += "<td class='text-center'>" + convertDate(v.time, 1) + "</td>";
                tr += "<td class='text-right'>" + v.use_count + "</td>";
                tr += "<td class='text-center'>" +
                    "<a href='javascript:void(0)' onclick='templateObj.modifyBaseForm(" + v.id + ")'>" +
                    "查看 / 修改" +
                    "</a>" +
                    "</td>";
                tr += "<td class='text-center'><a href='javascript:void(0)' onclick='templateObj.modifyDetailForm(" + v.id + ")'>" +
                    "查看 / 修改" +
                    "</a>" +
                    "</td>";
                tr += "<td class='text-center'>";
                if (v.use_count == 0 && v.is_default != 1) {
                    tr += "<a href='javascript:void(0)' onclick='templateObj.del(" + v.id + ")'>删除 </a>";
                } else {
                    tr += " / ";
                }

                tr += "</td>";
                tr += "</tr>";
            });

            if (tr == "") {
                tr = "<tr><td colspan='9' class='text-center'>--</td></tr>";
            }

            $("#template_lists_table>tbody").html(tr);
        })
    },

    /**
     * 手续费详情
     * @param id
     */
    info: function (id) {
        show_loading_table('assign_template_table', 3);

        var tbody = $("#assign_template_table").find('tbody');
        if (id == 0) {
            tbody.html("<tr><td colspan='3' class='text-center'>--</td></tr>");
            return false;
        }

        $.getJSON('/template/detail', {id: id}, function (json) {
            if (json.code != 1) {
                new PNotify({
                    title: '错误提醒',
                    text: json.msg,
                    delay: 5000,
                    styling: 'bootstrap3'
                });
                return false;
            }

            var tr = "";
            $.each(json.detail, function (i, v) {
                tr += "<tr>" +
                    "<td width='40%'>" + v.product + "</td>" +
                    "<td class='text-right'>" + parseFloat(v.trade_cost_open) + "</td>" +
                    "<td class='text-right'>" + parseFloat(v.trade_cost_close) + "</td>" +
                    "</tr>";
            });

            if (tr == "") {
                tr = "<tr><td colspan='2' class='text-center'>--</td></tr>";
            }

            tbody.html(tr);
        });
    },

    /**
     * 添加模板
     */
    addForm: function (type) {
        $.get('/template/add-form', function (html) {
            $('#modal_pop_title').html('添加手续费模板');
            $('#modal_pop_body').html(html);
            $(document).off('click', '#modal_pop_btn');
            $(document).on('click', '#modal_pop_btn', function () {
                templateObj.add(type);
            });
            $('#modal_pop').modal('show');
        });
    },

    /**
     * 提交模板
     */
    add: function (type) {
        var validFlag = true;
        var params = {};
        var search = $('#template_add_form').find('input,select,textarea');
        $.each(search, function (i, v) {
            var name = $(v).attr('name');
            if (name) {
                var val = $.trim($(v).val());
                if (name != 'desc' && $.trim($(v).val()) == "") {
                    validFlag = false;
                    $(v).focus();
                    new PNotify({
                        title: '错误提醒',
                        text: '必填项，不能为空',
                        delay: 5000,
                        styling: 'bootstrap3'
                    });

                    return false;
                }

                params[name] = val;
            }
        });

        if (!validFlag) return false;

        var ids = [];
        $.each($("#template_add_table").find("input[type=number]"), function (i, v) {
            var product = $(v).attr('data-product');
            var name = $(v).attr('name');
            var val = $.trim($(v).val());
            if (!val) {
                validFlag = false;
                $(v).focus();
                new PNotify({
                    title: '错误提醒',
                    text: '必填项，不能为空',
                    delay: 5000,
                    styling: 'bootstrap3'
                });

                return false;
            }

            val = parseFloat(val);
            var pushFlag = true;
            $.each(ids, function (i, v) {
                if (v == product) {
                    pushFlag = false;
                    return false;
                }
            });
            if (pushFlag) ids.push(product);

            params[name] = val;
        });

        if (!validFlag) return false;
        if (ids.length == 0) {
            new PNotify({
                title: '错误提醒',
                text: '模板中最少需要一个品种',
                delay: 5000,
                styling: 'bootstrap3'
            });
            return false;
        }
        params.ids = ids.join(',');
        console.log(params)

        $.post('/template/add', params, function (json) {
            var obj = {
                title: '操作通知',
                text: json.msg,
                styling: 'bootstrap3',
                delay: 5000,
                type: ''
            };
            if (json.code == 1) {
                $('#modal_pop').modal('hide');
                if (type == 1) {
                    templateObj.lists(1, 1);
                } else {
                    menu_detail['menu_15']['loadContent'] = true;
                    get_content('menu_15');
                }

                obj.type = 'info';
                obj.addclass = 'dark';
            } else {
                obj.type = 'error';
            }
            new PNotify(obj);
        }, 'json');
    },

    /**
     * 删除模板
     * 默认模板和已分配模板不能删除
     *
     * @param id
     */
    del: function (id) {
        swal({
            title: '确定删除此模板吗?',
            text: "慎用，删除后不可恢复",
            type: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then(function () {
            $.getJSON('/template/del', {id: id}, function (json) {
                var obj = {
                    title: '操作通知',
                    text: json.msg,
                    styling: 'bootstrap3',
                    delay: 5000,
                    type: ''
                };
                if (json.code == 1) {
                    $('#modal_pop').modal('hide');
                    templateObj.lists(3, 0);
                    obj.type = 'info';
                    obj.addclass = 'dark';
                } else {
                    obj.type = 'error';
                }
                new PNotify(obj);
            });
        }, function (dismiss) {

        });
    },

    /**
     * 基本信息表单
     * @param id
     */
    modifyBaseForm: function (id) {
        $.get('/template/modify-base-form', {id: id}, function (html) {
            $('#modal_pop_title').html('修改模板基本信息');
            $('#modal_pop_body').html(html);
            $(document).off('click', '#modal_pop_btn');
            $(document).on('click', '#modal_pop_btn', function () {
                templateObj.modifyBase(id);
            });
            $('#modal_pop').modal('show');
        });
    },

    /**
     * 提交基本信息设置
     * @param id
     */
    modifyBase: function (id) {
        var validFlag = true;
        var params = {};
        params.id = id;
        var search = $('#template_add_form').find('input,select,textarea');
        $.each(search, function (i, v) {
            var name = $(v).attr('name');
            if (name) {
                var val = $.trim($(v).val());
                if (name != 'desc' && $.trim($(v).val()) == "") {
                    validFlag = false;
                    $(v).focus();
                    new PNotify({
                        title: '错误提醒',
                        text: '必填项，不能为空',
                        delay: 5000,
                        styling: 'bootstrap3'
                    });

                    return false;
                }

                params[name] = val;
            }
        });

        if (!validFlag) return false;
        $.post('/template/modify-base', params, function (json) {
            var obj = {
                title: '操作通知',
                text: json.msg,
                styling: 'bootstrap3',
                delay: 5000,
                type: ''
            };
            if (json.code == 1) {
                $('#modal_pop').modal('hide');
                templateObj.lists(3, 0);

                obj.type = 'info';
                obj.addclass = 'dark';
            } else {
                obj.type = 'error';
            }
            new PNotify(obj);
        }, 'json');
    },

    /**
     * 详细信息表单
     * @param id
     */
    modifyDetailForm: function (id) {
        $.get('/template/modify-detail-form', {id: id}, function (html) {
            $('#modal_pop_title').html('修改模板品种、手续费信息');
            $('#modal_pop_body').html(html);
            $(document).off('click', '#modal_pop_btn');
            $(document).on('click', '#modal_pop_btn', function () {
                templateObj.modifyDetail(id)
            });
            $('#modal_pop').modal('show');
        });
    },

    /**
     * 提交详细信息设置
     * @param id
     */
    modifyDetail: function (id) {
        var validFlag = true;
        var params = {};
        params['template_id'] = id;
        params['_csrf-backend'] = $('input[name=_csrf-backend]').val();

        var ids = [];
        $.each($("#template_modify_detail_table").find("input[type=number]"), function (i, v) {
            var product = $(v).attr('data-product');
            var name = $(v).attr('name');
            var val = $.trim($(v).val());
            if (!val) {
                validFlag = false;
                $(v).focus();
                new PNotify({
                    title: '错误提醒',
                    text: '必填项，不能为空',
                    delay: 5000,
                    styling: 'bootstrap3'
                });

                return false;
            }

            val = parseFloat(val);
            var pushFlag = true;
            $.each(ids, function (i, v) {
                if (v == product) {
                    pushFlag = false;
                    return false;
                }
            });
            if (pushFlag) ids.push(product);

            params[name] = val;
        });
        if (!validFlag) return false;
        if (ids.length == 0) {
            new PNotify({
                title: '错误提醒',
                text: '请选择至少一个品种',
                delay: 5000,
                styling: 'bootstrap3'
            });

            return false;
        }
        params.ids = ids.join(',');

        $.post('/template/modify-detail', params, function (json) {
            var obj = {
                title: '操作通知',
                text: json.msg,
                styling: 'bootstrap3',
                delay: 5000,
                type: ''
            };
            if (json.code == 1) {
                obj.type = 'info';
                obj.addclass = 'dark';
            } else {
                obj.type = 'error';
            }
            new PNotify(obj);
        }, 'json');
    },

    /**
     * 从现有模板中选择参考的模板
     *
     * @param id
     */
    compare: function (id) {
        $.getJSON('/template/detail', {id: id}, function (json) {
            if (json.code != 1) {
                new PNotify({
                    title: '错误提醒',
                    text: json.msg,
                    delay: 5000,
                    styling: 'bootstrap3'
                });
                return false;
            }

            var obj = $("#template_add_table");
            $.each(json.detail, function (i, v) {
                var tmp;
                tmp = obj.find("input[name=" + v.product + "_open]");
                tmp.val(v.trade_cost_open);

                tmp = obj.find("input[name=" + v.product + "_close]");
                tmp.val(v.trade_cost_close);
            })
        });
    }
};